package com.dz.finance.common.utils;

import com.dz.finance.common.constant.ApiResponseCode;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: DengHaoQi
 * @date: 2024/5/22 16:21
 * @description: 统一返回数据结果
 */

@Data
public class Result<T> {

    private Integer code;
    private String codeMessage;
    private Boolean success;
    private T data;
    private Map<String, String> errorMessage;   // 可能有多个错误



    public static <T> Result<T> ok(T data) {
       Result<T> result = new Result<>();
       result.setCode(ApiResponseCode.SUCCESS.getCode());
       result.setData(data);
       result.setCodeMessage(ApiResponseCode.SUCCESS.getMessage());
       result.setSuccess(true);
       return result;
    }


    public static <T> Result<T> ok() {
        return ok(null);
    }


    public static <T> Result<T> error(String error) {
        Map<String, String> errors = new HashMap<>();
        errors.put(error, error);
        return error(errors);
    }


    public static <T> Result<T> error(Map<String, String> errorMessage) {
        Result<T> result = new Result<>();
        result.setCode(ApiResponseCode.SERVICE_ERROR.getCode());
        result.setData(null);
        result.setCodeMessage(ApiResponseCode.SERVICE_ERROR.getMessage());
        result.setErrorMessage(errorMessage);
        result.setSuccess(false);
        return result;
    }


    public Result<T> error(String msg, T data) {
        this.setData(data);
        this.setSuccess(false);
        this.setCode(ApiResponseCode.SERVICE_ERROR.getCode());
        this.setCodeMessage(ApiResponseCode.SERVICE_ERROR.getMessage());
        return this;
    }


    public Result<T> error(Integer code, Map<String, String> errors) {
        this.setCode(code);
        this.setErrorMessage(errors);
        this.setData(data);
        this.setSuccess(false);
        return this;
    }

}
